package pe.edu.upla.lamerced.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.DynaActionForm;
import org.apache.struts.actions.DispatchAction;
import org.springframework.beans.factory.annotation.Autowired;

import pe.edu.upla.lamerced.bean.Authorities;
import pe.edu.upla.lamerced.bean.AuthoritiesId;
import pe.edu.upla.lamerced.bean.Users;
import pe.edu.upla.lamerced.service.UsuarioService;
import pe.edu.upla.lamerced.utiles.Utiles;

public class LoginAction extends DispatchAction {

	private static final Logger logger = Logger.getLogger(LoginAction.class);
	
	@Autowired
	UsuarioService usuarioService;
	
	public ActionForward login(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response)	throws Exception {
		try {
            
			String usuario = request.getParameter("username");
            String password = request.getParameter("password");
            logger.debug(usuario+ " / " + password);
		} catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msgError", e.getMessage());
            return mapping.findForward("login");
		}
		return mapping.findForward("home");
	}
	public ActionForward logout(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response)	throws Exception {
		try {
			logger.debug(" logout");
		} catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msgError", e.getMessage());
            return mapping.findForward("home");
		}
		return mapping.findForward("login");
	}
	
	public ActionForward detalle(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response)	throws Exception {
		try {
            logger.debug("detalle de usuario");
            request.setAttribute("duser", Users.getUsuarioBean());
		} catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msgError", e.getMessage());
		}
		return mapping.findForward("detalle");
	}
	
	public ActionForward preEdit(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response)	throws Exception {
		try {
            logger.debug("detalle de usuario");
            request.setAttribute("euser", Users.getUsuarioBean());
		} catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msgError", e.getMessage());
		}
		return mapping.findForward("edit");
	}
	
	public ActionForward edit(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response)	throws Exception {
		try {
            logger.debug("detalle de usuario");
            DynaActionForm myform = (DynaActionForm)form;
            Users us = Users.getUsuarioBean();
            us.setApeMaterno(myform.getString("apeMaterno"));
            us.setApePaterno(myform.getString("apePaterno"));
            us.setNombre(myform.getString("nombre"));
            us.setPassword(myform.getString("password"));
            //us.setNroDocumento(myform.getString("nroDocumento"));
            us.setTipo(Integer.parseInt(myform.getString("tipo")));
            usuarioService.modificarUsuario(us);
            //request.setAttribute("euser", Users.getUsuarioBean());
            request.setAttribute("mensaje", "Informacion modificada");
		} catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msgError", e.getMessage());
		}
		return mapping.findForward("procesosHome");
	}

	
	public ActionForward registro(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response)	throws Exception {
		try {
			logger.debug("  registro del usuario");
			Users usuario = new Users();
			
			usuario.setApePaterno(request.getParameter("paterno"));
			usuario.setApeMaterno(request.getParameter("materno"));
			usuario.setNombre(request.getParameter("nombre"));
			usuario.setNroDocumento(request.getParameter("documento"));
			usuario.setTipo(Integer.parseInt(request.getParameter("TipoCliente")));
			usuario.setUsername(request.getParameter("documento"));
			usuario.setPassword(request.getParameter("documento"));
			usuario.setEnabled(1);
			
			AuthoritiesId uid = new AuthoritiesId();
			uid.setAuthority("ROLE_CONSULTA");
			uid.setUsername(usuario.getUsername());
			Authorities au = new Authorities();
			au.setId(uid);
			au.setUsername(usuario);
			usuarioService.registrarUsuario(usuario,au);
			
			request.setAttribute("mensaje", "El usuario ha sido registrado correctamente. Su usuario y clave son su numero de documento");
		} catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msgError", e.getMessage());
		}
		return mapping.findForward("login");
	}
	

	/**
	 * Action para el resetero de clave
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ActionForward preCambio(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response)	throws Exception {
		try {
	
            logger.debug("pantala previa de cambio de clave");
            
		} catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msgError", e.getMessage());
		}
		return mapping.findForward("clave");
	}
	
	
	public ActionForward password(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response)	throws Exception {
		try {
	
            logger.debug("camvbiar password");
            String actual = request.getParameter("actual");
            String nueva = request.getParameter("nueva");
            String confirm = request.getParameter("confirm");
            
            Users ulogin = Users.getUsuarioBean();
            if(!Utiles.nullToBlank(actual).equals(ulogin.getPassword())){
            	request.setAttribute("msgError", "Su clave esta equivocada.");
            	return mapping.findForward("clave");
            }
            if(!Utiles.nullToBlank(nueva).equals(confirm)){
            	request.setAttribute("msgError", "Su nueva clave no coincide.");
            	return mapping.findForward("clave");
            }
            ulogin.setPassword(nueva);
            usuarioService.modificarUsuario(ulogin);
            request.setAttribute("mensaje", "Su clave ha sido modifcada correctamente");
		} catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msgError", e.getMessage());
		}
		return mapping.findForward("clave");
	}
	
	public ActionForward lclientes(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response)	throws Exception {
		try {
            
			request.setAttribute("lclientes", usuarioService.listaClientes());
			
		} catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msgError", e.getMessage());
            return mapping.findForward("login");
		}
		return mapping.findForward("clientes");
	}
	
}


